﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PrintAgentService;
using System.IO;
using Intex.Db.Models;
using System.Threading;
using System.Diagnostics;

namespace PrintingManagerSystem
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Init();
        }

        Thread trdPrint;
        DataSet dsTemplateConfig = new DataSet();
        int printIndex = -1;
        private bool ifTimerRunning = false;
        private int _printCount;
        object printCountLocker = new object();
        private int _timerSpan = 120;
        object timerLocker = new object();
        bool rangePrint = false;
        bool isPrinting = false;
        int rangeFrom = -1;
        int rangeTo = -1;
        string indexColumnName = "";
        bool printOnTime = false;
        DateTime startTime = DateTime.Now;
        int printerCheckSpan = 3000;
        bool autoLocate = false;
        int autoLocationIndex = 0;
        bool isPrintTotalNum = false;
        int printTotalNum = 0;
        int printCount = 0;
        int threadId = 0;
        DateTime lastQueryDate = new DateTime();
        Dictionary<int, int> orderList = new Dictionary<int, int>();

        public int PrintCount
        {
            get { return _printCount; }
            set
            {
                lock (printCountLocker)
                {
                    _printCount = value;
                }
            }
        }

        public int TimerSpan
        {
            get { return _timerSpan; }
            set
            {
                lock (timerLocker)
                {
                    _timerSpan = value;
                }
            }
        }

        public bool IfTimerRunning
        {
            get { return ifTimerRunning; }
            set
            {
                ifTimerRunning = value;
                if (value)
                {
                    this.btnStartPrint.Text = "停止";
                    this.btnStartPrint.BackColor = Color.LightCoral;
                    this.pnlButtonArea.Enabled = false;
                    this.pnlTimerSetting.Enabled = false;
                    this.dgvPrintingData.ReadOnly = true;
                }
                else
                {
                    this.btnStartPrint.Text = "开始";
                    this.btnStartPrint.BackColor = Color.LightGreen;
                    this.pnlButtonArea.Enabled = true;
                    this.pnlTimerSetting.Enabled = true;
                    this.dgvPrintingData.ReadOnly = false;
                }
                Application.DoEvents();
            }
        }

        void OnReOpen(object o, bool timeout)
        {
            this.Invoke(new MethodInvoker(() => { this.Activate(); }));
        }

        private void Init()
        {
            ThreadPool.RegisterWaitForSingleObject(Program.ewh, OnReOpen, null, -1, false);
            try
            {
                var pros = Process.GetProcesses();
                foreach (var p in pros)
                {
                    if (p.ProcessName == "EXCEL")
                    {
                        p.Kill();
                    }
                }
            }
            catch
            {
            }
            try
            {
                DirectoryInfo tempDir = new DirectoryInfo(PrintAgent.TempFilePath);
                if (!tempDir.Exists)
                {
                    tempDir.Create();
                }
                if (tempDir.Exists)
                {
                    var files = tempDir.GetFiles();
                    foreach (var f in files)
                    {
                        f.Delete();
                    }
                }
            }
            catch
            {
            }

            string strPrinterCheckSpan = System.Configuration.ConfigurationManager.AppSettings["PrinterCheckSpan"];
            if (!int.TryParse(strPrinterCheckSpan, out printerCheckSpan))
            {
                MessageBox.Show("打印机状态监测参数异常，请检查配置文件，现默认为3秒");
                printerCheckSpan = 3000;
            }

            this.nudPrintNum.Value = Properties.Settings.Default.PrintCount;
            this.nudSpan.Value = Properties.Settings.Default.TimerSpan;
            this.dtpPrintDate.Value = DateTime.Now;
            this.dtpStartDate.Value = DateTime.Now;

            trdPrint = new Thread(new ThreadStart(PrintTimerAgent));
            trdPrint.IsBackground = true;
            dsTemplateConfig.ReadXml(PrintAgent.ConfigFilePath + "TemplateLocatingConfig.xml");
            this.dgvPrintingData.RowHeadersWidth = 20;
            this.dgvPrintingData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            this.dgvPrintingData.MultiSelect = false;
            this.dgvPrintingData.CellEndEdit += new DataGridViewCellEventHandler(dgvPrintingData_CellEndEdit);

            Config.Create();
            foreach (var item in PrintAgent.PrinterArray)
            {
                this.lbxPrinterList.Items.Add(item);
            }
            setBeginTimeStatus(cbxStartTime.Checked);
            setBeginLine(cbxRangePrint.Checked);
            BindingDisplayData(DateTime.Now);
        }

        private void BindingDisplayData(DateTime? date = null)
        {
            lastQueryDate = this.dtpPrintDate.Value;
            this.dgvPrintingData.SelectionChanged -= dgvPrintingData_SelectionChanged;

            this.dgvPrintingData.Rows.Clear();

            Dictionary<string, ItemType> mapDic = new Dictionary<string, ItemType>();
            PrintAgent pa = new PrintAgent();
            DataTable dtSource = null;
            try
            {
                orderList = new Dictionary<int, int>();
                dtSource = pa.GetDisplayData(out mapDic, out orderList, date);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return;
            }

            if (dtSource != null && dtSource.Rows.Count > 0)
            {
                this.dgvPrintingData.Columns.Clear();
                int changeColId = 0;
                for (int i = 0; i < dtSource.Columns.Count; i++)
                {
                    var colId = this.dgvPrintingData.Columns.Add(dtSource.Columns[i].ColumnName, dtSource.Columns[i].ColumnName);
                    this.dgvPrintingData.Columns[colId].SortMode = DataGridViewColumnSortMode.NotSortable;
                    if (dtSource.Columns[i].ColumnName == "ItemId"
                        || dtSource.Columns[i].ColumnName == "TemplateFile"
                        || dtSource.Columns[i].ColumnName == "PrintStatus")
                    {
                        this.dgvPrintingData.Columns[colId].Visible = false;
                    }
                    this.dgvPrintingData.Columns[colId].ReadOnly = true;
                    if (dtSource.Columns[i].ColumnName == mapDic[Config.NameAlias].ItemName)
                    {
                        changeColId = colId;
                    }
                }
                if (dtSource != null && dtSource.Rows.Count > 0)
                {
                    for (int i = 0; i < dtSource.Rows.Count; i++)
                    {
                        int newRowIndex = this.dgvPrintingData.Rows.Add();
                        for (int col = 0; col < dtSource.Columns.Count; col++)
                        {
                            this.dgvPrintingData.Rows[newRowIndex].Cells[dtSource.Columns[col].ColumnName].Value = dtSource.Rows[i][col].ToString();
                            if (dtSource.Columns[col].ColumnName == "PrintStatus"
                                && dtSource.Rows[i][col].ToString() == "1")
                            {
                                this.dgvPrintingData.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;
                                this.dgvPrintingData.Rows[i].Cells[changeColId].ReadOnly = true;
                            }
                            else if (dtSource.Columns[col].ColumnName == "PrintStatus")
                            {
                                this.dgvPrintingData.Rows[i].Cells[changeColId].ReadOnly = false;
                            }
                        }
                        this.dgvPrintingData.Rows[newRowIndex].Tag = dtSource.Rows[i][mapDic[Config.IndexAlias].ItemName];
                    }
                }

                indexColumnName = mapDic[Config.IndexAlias].ItemName;
                //this.dgvPrintingData.Sort(this.dgvPrintingData.Columns[mapDic[Config.IndexAlias].ItemName], ListSortDirection.Ascending);
                if (autoLocate)
                {
                    this.autoLocate = false;
                    this.dgvPrintingData.FirstDisplayedScrollingRowIndex = autoLocationIndex;
                }
                dgvPrintingData_SelectionChanged(null, null);
            }
            if (!this.dgvPrintingData.Columns.Contains("deleteIndex") && this.dgvPrintingData.Rows.Count > 1)
            {
                this.dgvPrintingData.Columns.Insert(0, new DataGridViewCheckBoxColumn
                {
                    Name = "deleteIndex",
                    HeaderText = "",
                    Width = 20,
                    TrueValue = true,
                    FalseValue = false,
                    IndeterminateValue = false
                });
            }
            this.dgvPrintingData.SelectionChanged += new EventHandler(dgvPrintingData_SelectionChanged);

        }

        void dgvPrintingData_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            PMS.Log.Logger.Info("Event:dgvPrintingData onCellEndEdit");
            if (this.dgvPrintingData.Columns[e.ColumnIndex].Name == "deleteIndex") return;
            PrintAgent pa = new PrintAgent();
            int id = 0;
            string newName = this.dgvPrintingData.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();

            if (string.IsNullOrWhiteSpace(newName))
            {
                MessageBox.Show("值不能改为空");
            }
            else
            {
                if (int.TryParse(this.dgvPrintingData.Rows[e.RowIndex].Cells["ItemId"].Value.ToString(), out id))
                {
                    var res = pa.UpdateItemName(id, newName);
                    if (!res)
                    {
                        MessageBox.Show("修改失败，请重试");
                    }
                }
                else
                {
                    MessageBox.Show("修改失败，ItemId不正确，请检查数据");
                }
            }
            this.autoLocate = true;
            this.autoLocationIndex = e.RowIndex;
            ThreadPool.QueueUserWorkItem(new WaitCallback(
                x =>
                {
                    Thread.Sleep(500);
                    this.Invoke(new Action<object, EventArgs>(btnQuery_Click), new object[2] { null, null });
                }));
        }

        void dgvPrintingData_SelectionChanged(object sender, EventArgs e)
        {
            PMS.Log.Logger.Info("Event: dgvPrintingData on SelectionChanged");
            this.cmbNowPrintingInfo.Text = "";

            if (this.dgvPrintingData.SelectedRows.Count > 0)
            {
                try
                {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < this.dgvPrintingData.Columns.Count; i++)
                    {
                        sb.Append(this.dgvPrintingData.SelectedRows[0].Cells[i].Value == null ? "" : this.dgvPrintingData.SelectedRows[0].Cells[i].Value.ToString() + " ");
                    }
                    this.cmbNowPrintingInfo.Text = sb.ToString().TrimEnd();
                }
                catch(Exception ex)
                {
                    PMS.Log.Logger.Error(ex);
                }
            }
        }

        private void btnTestPrinting_Click(object sender, EventArgs e)
        {
            //PrintAgent pa = new PrintAgent();
            //pa.PrintExcel("F:\\门板TFTM3# 391A 023A标签最新版20130507.xls", this.lbxPrinterList.SelectedItem.ToString(), 4);
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (IfTimerRunning)
            {
                return;
            }
            PMS.Log.Logger.Info("Event:btnImport onClick");
            this.dgvPrintingData.Rows.Clear();
            if (!File.Exists(PrintAgent.ConfigFilePath + "ImportConfig.xml"))
            {
                MessageBox.Show("数据导入配置文件未找到");
                return;
            }
            DataSet dsConfig = new DataSet();

            try
            {
                dsConfig.ReadXml(PrintAgent.ConfigFilePath + "ImportConfig.xml");
            }
            catch
            {
                MessageBox.Show("数据导入配置文件读取失败");
                return;
            }

            if (DialogResult.OK == this.ofdImportFileSelect.ShowDialog())
            {
                PrintAgent pa = new PrintAgent();
                try
                {
                    var data = pa.GenerateImportData(this.ofdImportFileSelect.FileName, dsConfig);
                    GC.Collect();
                    if (data != null && data.Rows.Count > 0)
                    {
                        DateTime date = new DateTime();
                        if (DateTime.TryParse(data.Rows[0][Config.CreatedAlias].ToString(), out date))
                        {
                            var repeatedData = pa.ImportCheckRepeatedData(data);
                            if (repeatedData != null && repeatedData.Count > 0)
                            {
                                if (DialogResult.No == MessageBox.Show(string.Format("存在{0}条重复数据，是否覆盖导入", repeatedData.Count.ToString()), "提示", MessageBoxButtons.YesNo))
                                {
                                    return;
                                }
                                if (!pa.DeleteRepeatedData(repeatedData, date))
                                {
                                    MessageBox.Show("覆盖数据失败");
                                    return;
                                }
                            }
                            this.dtpPrintDate.Value = date;
                            var res = pa.ImportProduceData(data);
                            if (res)
                            {
                                MessageBox.Show("数据导入成功");
                            }
                            else
                            {
                                MessageBox.Show("数据导入失败");
                            }
                            btnQuery_Click(null, null);
                        }
                        else
                        {
                            MessageBox.Show("数据导入失败，导入的数据没有日期");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                //data.WriteXml("f:\\ImportedData.xml");
                BindingDisplayData(this.dtpPrintDate.Value);
                GC.Collect();
            }
        }

        private void btnStartPrint_Click(object sender, EventArgs e)
        {
            PMS.Log.Logger.Info("Event:btnStartPrint onClick");            
            if (this.btnStartPrint.Text == "开始")
            {
                if (this.dgvPrintingData.Rows.Count <= 0)
                {
                    MessageBox.Show("没有打印数据");                    
                    return;
                }
                if (!File.Exists(PrintAgent.ConfigFilePath + "TemplateLocatingConfig.xml"))
                {
                    MessageBox.Show("模版读取配置文件未找到");
                    return;
                }                
                if (Properties.Settings.Default.PrinterList.Count <= 0)
                {
                    MessageBox.Show("您尚未设置打印机");
                    return;
                }
                foreach (var p in Properties.Settings.Default.PrinterList)
                {
                    if (!PrintAgent.PrinterArray.Contains(p))
                    {
                        MessageBox.Show("您设置的打印机\"" + p + "\"不存在");
                        return;
                    }
                }
                if (trdPrint.IsAlive)
                {
                    MessageBox.Show("打印队列中仍有任务在进行，请稍候再重试！");
                    return;
                }
                //if (this.cbxRangePrint.Checked && this.nudRangeFrom.Value > this.nudRangeTo.Value)
                //{
                //    MessageBox.Show("打印范围设置不正确");
                //    return;
                //}
                foreach (var item in Properties.Settings.Default.PrinterList)
                {
                    try
                    {
                        if (!CPrintStatus.IsPrinterReady(item))
                        {
                            MessageBox.Show(string.Format("错误！请检查打印机{0}", item));
                            return;
                        }
                    }
                    catch
                    {
                        MessageBox.Show(string.Format("错误！请检查打印机{0}", item));
                        return;
                    }
                }


                printOnTime = this.cbxStartTime.Checked;
                //startTime = new DateTime((int)this.nudHour.Value, (int)this.nudMin.Value, (int)this.nudSec.Value);
                if (dtpStartDate.Value < DateTime.Now)
                {
                    dtpStartDate.Value = DateTime.Now;
                }
                startTime = new DateTime(dtpStartDate.Value.Year, dtpStartDate.Value.Month, dtpStartDate.Value.Day, (int)this.nudHour.Value, (int)this.nudMin.Value, (int)this.nudSec.Value);
                this.rangePrint = this.cbxRangePrint.Checked;
                rangeFrom = (int)this.nudRangeFrom.Value;
                rangeTo = (int)this.nudRangeTo.Value;
                printIndex = -1;
                isPrintTotalNum = this.cbxPrintTotalNum.Checked;
                printTotalNum = (int)this.nudPrintTotalNum.Value;
                printCount = 0;
                for (int i = 0; i < orderList.Count; i++)
                {
                    if (this.rangePrint)
                    {
                        if (orderList.ElementAt(i).Key == rangeFrom)
                        {
                            printIndex = orderList.ElementAt(i).Key;
                            break;
                        }
                    }
                    else
                    {
                        if (this.dgvPrintingData.Rows[i].DefaultCellStyle.BackColor != Color.LightGreen)
                        {
                            printIndex = orderList.ElementAt(i).Key;
                            break;
                        }
                    }
                }
                if (isPrintTotalNum && printIndex == -1)
                {
                    ContinuePrint();
                }
                if (printIndex == -1)
                {
                    MessageBox.Show("没有需要打印的数据");
                    return;
                }
                //if (threadId > 0) return;
                PMS.Log.Logger.Info(new
                {
                    StartIndex = nudRangeFrom.Value,
                    IsRange = cbxRangePrint.Checked,
                    PrintTotal = this.nudPrintTotalNum.Value,
                    StartDate = this.dtpStartDate.Value,
                    IsStartTime = this.cbxStartTime.Checked,
                    StartHour = this.nudHour.Value,
                    StartMin = this.nudMin.Value,
                    TimeSpan = this.nudSpan.Value
                });
                this.PrintCount = (int)this.nudPrintNum.Value;
                this.TimerSpan = (int)this.nudSpan.Value * 1000;
                IfTimerRunning = true;
                //Debug.WriteLine(trdPrint.ThreadState);
                if (trdPrint.ThreadState!=System.Threading.ThreadState.Unstarted)
                {
                    trdPrint = new Thread(new ThreadStart(PrintTimerAgent));
                    trdPrint.IsBackground = true;                
                }                           
                this.trdPrint.Start();
                //trdPrint = new Thread(new ThreadStart(PrintTimerAgent));
                //trdPrint.IsBackground = true;
                //this.trdPrint.Start();
            }
            else
            {
                IfTimerRunning = false;
                threadSync.Set();
            }
        }
        AutoResetEvent threadSync = new AutoResetEvent(false);
        void PrintTimerAgent()
        {
            //if (Thread.CurrentThread.ManagedThreadId != threadId) return;
            while (IfTimerRunning)
            {
                if (printOnTime)
                {
                    if (startTime > DateTime.Now)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }
                    printOnTime = false;
                }
                try
                {
                    PrintTimerHandler(printIndex, this.PrintCount, false, true);
                    printIndex++;
                    printCount++;
                    
                }
                catch (Exception e)
                {
                    PMS.Log.Logger.Error(e);
                    
                }
                this.Invoke(new MethodInvoker(IsPrintEnd));
                if (IfTimerRunning)
                {
                    threadSync.WaitOne(this.TimerSpan);
                    //Thread.Sleep(this.TimerSpan);
                }
            }
            threadId = 0;
        }

        private void IsPrintEnd()
        {
            if (isPrintTotalNum)
            {
                if (printCount >= printTotalNum)
                {
                    IfTimerRunning = false;
                    return;
                }
            }
            if (orderList.Count < printIndex)
            {
                if (isPrintTotalNum)
                {
                    if (printCount >= printTotalNum)
                    {
                        IfTimerRunning = false;
                        return;
                    }
                    ContinuePrint();
                    if (printIndex == -1)
                    {
                        MessageBox.Show("没有需要打印的数据"); 
                        IfTimerRunning = false;
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    IfTimerRunning = false;
                }
            }
        }



        void ContinuePrint()
        {
            if (isPrintTotalNum)
            {
                int count = 1;
                while (count <= Config.MaxDay)
                {
                    this.dtpPrintDate.Value = lastQueryDate.AddDays(1);
                    BindingDisplayData(this.dtpPrintDate.Value);
                    printIndex = -1;
                    if (orderList.Count > 0)
                    {
                        printIndex = orderList.ElementAt(0).Key;
                        break;
                    }
                    else
                    {
                        count++;
                    }
                }
            }
        }

        private void PrintTimerHandler(int rowIndex, int printCount, bool printFinished, bool changeStatus)
        {
            if (orderList.Count < rowIndex)
            {
                this.Invoke(new MethodInvoker(() => { IfTimerRunning = false; }));
                
                return;
            }
            //if ((!printFinished)
            //    && this.dgvPrintingData.Rows[rowIndex].Cells["PrintStatus"].Value.ToString() == "1")
            //{
            //    return;
            //}
            Dictionary<string, ItemType> mapDic = new Dictionary<string, ItemType>();
            PrintAgent pa = new PrintAgent();

            if (orderList.Keys.Any(k => k == rowIndex))  //(long.TryParse(this.dgvPrintingData.Rows[rowIndex].Cells["ItemId"].Value.ToString(), out tempId))
            {
                int tempId = orderList[rowIndex];
                this.Invoke(new Action<int>(_rowindex => { this.dgvPrintingData.Rows[_rowindex].Selected = true; }), rowIndex - 1);

                List<long> ids = new List<long>();
                ids.Add(tempId);
                Dictionary<int, int> tempOrderList = new Dictionary<int, int>();
                var printData = pa.GetPrintData(out mapDic, out tempOrderList, ids);
                if (printData != null
                    && printData.Columns.Contains("TemplateFile")
                    && printData.Rows.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 1; i < this.dgvPrintingData.Rows[rowIndex - 1].Cells.Count; i++)
                    {
                        sb.Append(this.dgvPrintingData.Rows[rowIndex - 1].Cells[i].Value.ToString() + " ");
                    }
                    this.Invoke(new Action<string>(x => { this.cmbNowPrintingInfo.Text = x; }), sb.ToString().TrimEnd());

                    //this.cmbNowPrintingInfo.Text = sb.ToString().TrimEnd();
                    string displaytext = "\r\nItemId:" + orderList[rowIndex].ToString() + "\r\nRow Index: " + rowIndex.ToString() + "\r\nTag: " + this.dgvPrintingData.Rows[rowIndex - 1].Tag.ToString() + "\r\nData:" + sb.ToString().TrimEnd();

                    int nowPrinterIndex = 0;
                    bool finish = true;
                    for (int i = 0; i < printData.Rows.Count; i++)
                    {
                        bool isExcept = false;
                        var row = printData.Rows[i];
                        var templateFilePath = PrintAgent.TemplateFilePath + row["TemplateFile"].ToString();
                        if (File.Exists(templateFilePath))
                        {
                            do
                            {
                                try
                                {
                                    var tempFile = pa.PrintLabel(templateFilePath, mapDic, row, dsTemplateConfig);
                                    GC.Collect();
                                    for (int iprint = 0; iprint < printCount; iprint++)
                                    {
                                        if (!CPrintStatus.IsPrinterReady(Properties.Settings.Default.PrinterList[nowPrinterIndex], printerCheckSpan))
                                        {
                                            this.Invoke(new MethodInvoker(() => { this.cmbNowPrintingInfo.Text = string.Format("错误！请检查打印机{0}", Properties.Settings.Default.PrinterList[nowPrinterIndex]); }));

                                            while (IfTimerRunning && !CPrintStatus.IsPrinterReady(Properties.Settings.Default.PrinterList[nowPrinterIndex], printerCheckSpan))
                                            {
                                                Thread.Sleep(500);
                                                Application.DoEvents();
                                            }
                                        }
                                        pa.PrintExcel(tempFile, Properties.Settings.Default.PrinterList[nowPrinterIndex]);
                                        Debug.WriteLine("Print:Index:{0};template:{1};printer:{2}", rowIndex, tempFile, Properties.Settings.Default.PrinterList[nowPrinterIndex]);
                                        Debug.WriteLine("ThreadId:{0}", Thread.CurrentThread.ManagedThreadId);
                                        GC.Collect();
                                    }
                                    if (!pa.SetPrintSymbol((int)tempId, displaytext + "\r\n" + i.ToString(), printData))
                                    {
                                        finish = false;
                                    }
                                    else
                                    {
                                        finish = true;
                                    }
                                    isExcept = false;
                                }
                                catch (Exception e)
                                {
                                    //finish = false;
                                    isExcept = true;
                                    PMS.Log.Logger.Error(e);

                                }
                                if (isExcept)
                                {
                                    Thread.Sleep(500);
                                    Application.DoEvents();
                                }
                            } while (isExcept);
                        }
                        else
                        {
                            finish = false;
                            PMS.Log.Logger.Error("模板文件不存在");
                        }
                        nowPrinterIndex++;
                        if (nowPrinterIndex >= Properties.Settings.Default.PrinterList.Count) nowPrinterIndex = 0;
                    }
                    if (finish && changeStatus)
                    {
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.dgvPrintingData.Rows[rowIndex - 1].Cells["PrintStatus"].Value = "1";
                            this.dgvPrintingData.Rows[rowIndex - 1].Cells["打印状态"].Value = "已打印";
                            this.dgvPrintingData.Rows[rowIndex - 1].DefaultCellStyle.BackColor = Color.LightGreen;
                        }));
                    }
                }
            }
            else
            {
                PMS.Log.Logger.Warnning("Can't Find the Row");
            }
        }

        private void btnPrinterSetting_Click(object sender, EventArgs e)
        {
            if (IfTimerRunning)
            {
                return;
            }
            PMS.Log.Logger.Info("Event:btnPrinterSetting onClick");
            PrinterSetting ps = new PrinterSetting();
            ps.ShowDialog();
        }

        private void btnAppend_Click(object sender, EventArgs e)
        {            
            if (IfTimerRunning)
            {
                return;
            }
            PMS.Log.Logger.Info("Event:btnAppend onClick");
            if (!File.Exists(PrintAgent.ConfigFilePath + "ImportConfig.xml"))
            {
                MessageBox.Show("数据导入配置文件未找到");
                return;
            }
            DataSet dsConfig = new DataSet();

            try
            {
                dsConfig.ReadXml(PrintAgent.ConfigFilePath + "ImportConfig.xml");
            }
            catch
            {
                MessageBox.Show("数据导入配置文件读取失败");
                return;
            }
            if (this.dgvPrintingData.SelectedRows.Count <= 0)
            {
                MessageBox.Show("请选择一条记录作为插入点");
                return;
            }
            if (DialogResult.OK == this.ofdImportFileSelect.ShowDialog())
            {
                PrintAgent pa = new PrintAgent();
                IEnumerable<string> redundantIds = new List<string>();
                try
                {
                    var data = pa.GenerateImportData(this.ofdImportFileSelect.FileName, dsConfig);
                    GC.Collect();
                    DateTime date = new DateTime();
                    if (data != null && data.Rows.Count > 0)
                    {
                        if (DateTime.TryParse(data.Rows[0][Config.CreatedAlias].ToString(), out date))
                        {
                            if (date.Year != this.dtpPrintDate.Value.Year
                                || date.Month != this.dtpPrintDate.Value.Month
                                || date.Day != this.dtpPrintDate.Value.Day)
                            {
                                MessageBox.Show("请追加与当前计划日期相同的数据");
                                return;
                            }
                            //var repeatedData = pa.ImportCheckRepeatedData(data);
                            //if (repeatedData != null && repeatedData.Count > 0)
                            //{
                            //    if (DialogResult.No == MessageBox.Show(string.Format("存在{0}条重复数据，是否覆盖导入", repeatedData.Count.ToString()), "提示", MessageBoxButtons.YesNo))
                            //    {
                            //        return;
                            //    }
                            //    pa.DeleteRepeatedData(repeatedData, date);
                            //}


                            if (!pa.AppendProduceData(data, int.Parse(this.dgvPrintingData.SelectedRows[0].Tag.ToString())))
                            {
                                MessageBox.Show("数据追加失败");
                            }
                            else
                            {
                                MessageBox.Show("数据追加成功");
                            }
                        }
                        else
                        {
                            MessageBox.Show("数据导入失败，导入的数据没有日期");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                //data.WriteXml("f:\\ImportedData.xml");
                BindingDisplayData(this.dtpPrintDate.Value);
                GC.Collect();
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (IfTimerRunning)
            {
                return;
            }
            PMS.Log.Logger.Info("Event:btnDel onClick");
            try
            {
                string filePath = Config.DBBackupPath + Guid.NewGuid().ToString() + ".sqlite";
                System.IO.File.Copy(Config.DbFile, filePath);
                PMS.Log.Logger.Info("Backup File:" + filePath);
            }
            catch (Exception ex)
            {
                PMS.Log.Logger.Error(ex);
                return;
            }
            List<int> itemId = new List<int>();
            int continuCount = 0;
            PrintAgent pa = new PrintAgent();
            bool isDelete = false;
            int indexQuantity = 0;
            foreach (DataGridViewRow item in this.dgvPrintingData.Rows)
            {
                var checkBox = item.Cells["deleteIndex"] as DataGridViewCheckBoxCell;
                int tempInt = int.Parse(item.Tag.ToString());
                if (Boolean.Parse(checkBox.EditingCellFormattedValue.ToString()))
                {
                    itemId.Add(int.Parse(item.Cells["ItemId"].Value.ToString()));
                }
                else
                {

                    if (itemId.Count > 0)
                    {
                        isDelete = pa.DeleteDisplayData(itemId, continuCount - indexQuantity, this.dtpPrintDate.Value);
                    }
                    continuCount = tempInt;
                    indexQuantity += itemId.Count;
                    itemId.Clear();
                }


            }
            if (isDelete || itemId.Count > 0)
            {
                if (itemId.Count > 0)
                {
                    pa.DeleteDisplayData(itemId, continuCount - indexQuantity, this.dtpPrintDate.Value);
                }
                BindingDisplayData(this.dtpPrintDate.Value);
                return;
            }
            if (this.dgvPrintingData.SelectedRows.Count > 0)
            {
                if (pa.DeleteDisplayData(int.Parse(this.dgvPrintingData.SelectedRows[0].Cells["ItemId"].Value.ToString()), int.Parse(this.dgvPrintingData.SelectedRows[0].Tag.ToString()), this.dtpPrintDate.Value))
                {
                    this.dgvPrintingData.Rows.Remove(this.dgvPrintingData.SelectedRows[0]);
                    BindingDisplayData(this.dtpPrintDate.Value);
                }
                else
                {
                    MessageBox.Show("删除失败，请重试");
                }
            }
            else
            {

                MessageBox.Show("请选择要删除的记录");
            }
        }

        private void btnShiftUp_Click(object sender, EventArgs e)
        {
            if (IfTimerRunning)
            {
                return;
            }
            PMS.Log.Logger.Info("Event:btnShiftUp onClick");
            if (this.dgvPrintingData.SelectedRows.Count > 0)
            {
                if (this.dgvPrintingData.SelectedRows[0].Index > 0)
                {
                    PrintAgent pa = new PrintAgent();
                    if (pa.ChangeDisplayDataIndex(this.dtpPrintDate.Value, int.Parse(this.dgvPrintingData.SelectedRows[0].Tag.ToString()), int.Parse(this.dgvPrintingData.Rows[this.dgvPrintingData.SelectedRows[0].Index - 1].Tag.ToString())))
                    {
                        var delRow = this.dgvPrintingData.SelectedRows[0];
                        int newRowIndex = this.dgvPrintingData.SelectedRows[0].Index - 1;

                        string tempIndex = this.dgvPrintingData.Rows[newRowIndex].Cells[indexColumnName].Value.ToString();
                        this.dgvPrintingData.Rows[newRowIndex].Cells[indexColumnName].Value = delRow.Cells[indexColumnName].Value;
                        delRow.Cells[indexColumnName].Value = tempIndex;

                        this.dgvPrintingData.Rows.Remove(delRow);
                        this.dgvPrintingData.Rows.Insert(newRowIndex, delRow);
                        this.dgvPrintingData.Rows[newRowIndex].Selected = true;
                    }
                    else
                    {
                        MessageBox.Show("上移失败，请重试");
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择要上移的记录");
            }
        }

        private void btnShiftDown_Click(object sender, EventArgs e)
        {
            if (IfTimerRunning)
            {
                return;
            }
            PMS.Log.Logger.Info("Event:btnShiftDown onClick");
            if (this.dgvPrintingData.SelectedRows.Count > 0)
            {
                if (this.dgvPrintingData.SelectedRows[0].Index < this.dgvPrintingData.Rows.Count - 1)
                {
                    PrintAgent pa = new PrintAgent();
                    if (pa.ChangeDisplayDataIndex(this.dtpPrintDate.Value, int.Parse(this.dgvPrintingData.SelectedRows[0].Tag.ToString()), int.Parse(this.dgvPrintingData.Rows[this.dgvPrintingData.SelectedRows[0].Index + 1].Tag.ToString())))
                    {
                        var delRow = this.dgvPrintingData.SelectedRows[0];
                        int newRowIndex = this.dgvPrintingData.SelectedRows[0].Index + 1;

                        string tempIndex = this.dgvPrintingData.Rows[newRowIndex].Cells[indexColumnName].Value.ToString();
                        this.dgvPrintingData.Rows[newRowIndex].Cells[indexColumnName].Value = delRow.Cells[indexColumnName].Value;
                        delRow.Cells[indexColumnName].Value = tempIndex;

                        this.dgvPrintingData.Rows.Remove(delRow);
                        this.dgvPrintingData.Rows.Insert(newRowIndex, delRow);
                        this.dgvPrintingData.Rows[newRowIndex].Selected = true;
                    }
                    else
                    {
                        MessageBox.Show("下移失败，请重试");
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择要上移的记录");
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {            
            if (IfTimerRunning)
            {
                return;
            }
            PMS.Log.Logger.Info("Event:btnQuery onClick");
            BindingDisplayData(this.dtpPrintDate.Value);
            
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.IfTimerRunning)
            {
                if (DialogResult.Yes == MessageBox.Show("打印工作正在进行，确定要退出吗？", "提示", MessageBoxButtons.YesNo))
                {
                    ifTimerRunning = false;
                    Properties.Settings.Default.TimerSpan = (int)this.nudSpan.Value;
                    Properties.Settings.Default.PrintCount = (int)this.nudPrintNum.Value;
                    Properties.Settings.Default.Save();
                }
                else
                {
                    e.Cancel = true;
                }
            }
            else
            {
                Properties.Settings.Default.TimerSpan = (int)this.nudSpan.Value;
                Properties.Settings.Default.PrintCount = (int)this.nudPrintNum.Value;
                Properties.Settings.Default.Save();
            }
        }

        private void btnPrintAgain_Click(object sender, EventArgs e)
        {
            if (IfTimerRunning)
            {
                return;
            }
            PMS.Log.Logger.Info("Event:btnPrintAgain onClick");
            if (this.dgvPrintingData.SelectedRows.Count <= 0)
            {
                MessageBox.Show("请选择要再次打印的记录");
                return;
            }
            PrintTimerHandler(this.dgvPrintingData.SelectedRows[0].Index + 1, 1, true, false);
        }

        private void btnPrintSingle_Click(object sender, EventArgs e)
        {
            if (IfTimerRunning)
            {
                return;
            }
            PMS.Log.Logger.Info("Event:btnPrintSingle onClick");
            //if (this.dgvPrintingData.SelectedRows.Count <= 0)
            //{
            //    MessageBox.Show("请选择要进行单品打印的记录");
            //    return;
            //}
            //Dictionary<string, ItemType> mapDic = new Dictionary<string, ItemType>();
            //PrintAgent pa = new PrintAgent();
            //long tempId = 0;
            //if (long.TryParse(this.dgvPrintingData.Rows[this.dgvPrintingData.SelectedRows[0].Index].Cells["ItemId"].Value.ToString(), out tempId))
            //{
            //    List<long> ids = new List<long>();
            //    ids.Add(tempId);
            //    var printData = pa.GetPrintData(out mapDic, ids);
            //    if (printData != null
            //        && printData.Columns.Contains("TemplateFile")
            //        && printData.Rows.Count > 0)
            //    {
            //        SinglePrinterPrint spp = new SinglePrinterPrint();
            //        spp.Init(printData, mapDic, this.dsTemplateConfig, printerCheckSpan);
            //        spp.ShowDialog();
            //    }
            //}
            SinglePrinterPrint spp = new SinglePrinterPrint();
            spp.Init(this.dsTemplateConfig, printerCheckSpan);
            spp.ShowDialog();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DateTime date = DateTime.Parse("2013-08-10");
            if (DateTime.Now > date)
            {
                MessageBox.Show("请更新程序文件后使用。");
                this.Close();
            }
            date.AddDays(-10);
            if (DateTime.Now > date)
            {
                MessageBox.Show("测试版本即将过期，请及时更新文件。");
            }

        }

        private void btnImportFundamental_Click(object sender, EventArgs e)
        {
            if (IfTimerRunning)
            {
                return;
            }
            PMS.Log.Logger.Info("Event:btnImportFundamental onClick");
            if (!File.Exists(PrintAgent.ConfigFilePath + "FundamentImportConfig.xml"))
            {
                MessageBox.Show("数据导入配置文件未找到");
                return;
            }
            DataSet dsConfig = new DataSet();

            try
            {
                dsConfig.ReadXml(PrintAgent.ConfigFilePath + "FundamentImportConfig.xml");
            }
            catch
            {
                MessageBox.Show("数据导入配置文件读取失败");
                return;
            }

            if (DialogResult.OK == this.ofdImportFileSelect.ShowDialog())
            {
                PrintAgent pa = new PrintAgent();
                var res = pa.ImportFundamentalData(this.ofdImportFileSelect.FileName, dsConfig);
                GC.Collect();
                if (res)
                {
                    MessageBox.Show("基础数据导入成功");
                }
                else
                {
                    MessageBox.Show("基础数据导入失败");
                }
                //data.WriteXml("f:\\ImportedData.xml");
                BindingDisplayData(this.dtpPrintDate.Value);
                GC.Collect();
            }
        }

        private void btnTemplateExplorer_Click(object sender, EventArgs e)
        {
            if (IfTimerRunning)
            {
                return;
            }
            PMS.Log.Logger.Info("Event:btnTemplateExplorer onClick");
            if (Directory.Exists(PrintAgent.TemplateFilePath))
            {
                Process.Start("explorer.exe", PrintAgent.TemplateFilePath);
            }
            else
            {
                MessageBox.Show("模板目录不存在");
            }
        }

        private void btnMaintain_Click(object sender, EventArgs e)
        {
            if (IfTimerRunning)
            {
                return;
            }
            PMS.Log.Logger.Info("Event:btnMaintain onClick");
            ItemTypeMaintenance itm = new ItemTypeMaintenance();
            itm.ShowDialog();
        }

        private void cbxRangePrint_CheckedChanged(object sender, EventArgs e)
        {
            //PMS.Log.Logger.Info("Event:cbxRangePrint onCheckedChanged");
            this.cbxPrintTotalNum.Checked = this.cbxRangePrint.Checked;
            setBeginLine(cbxRangePrint.Checked);
        }

        private void cbxStartTime_CheckedChanged(object sender, EventArgs e)
        {
            setBeginTimeStatus(cbxStartTime.Checked);
        }

        private void setBeginTimeStatus(bool status)
        {
            dtpStartDate.Enabled = status;
            nudHour.Enabled = status;
            nudMin.Enabled = status;
        }

        private void setBeginLine(bool status)
        {
            nudRangeFrom.Enabled = status;
            nudPrintTotalNum.Enabled = status;
        }

    }
}
